/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * InventoryList.java
 *
 * Created on 13-dec-2011, 15:14:21
 */
package view.manage.inventory;

import javax.swing.table.DefaultTableModel;
import java.util.List;
import javax.swing.JOptionPane;
import main.WinkelApplication;
import model.Product;
import model.Category;


/**
 *
 * @author Nico de Groot
 * 
 * This class builds the inventory stock page.
 * It has a table in it where the name of the product and the stock are being displayed.
 * The stock can be edited in the table and submitted by the "editButton".
 * You can also filter the products displayed in the table by category and by product name.
 */
public class InventoryList extends javax.swing.JPanel {
    
    private String filterCategory = null;
    private String filterProductName = null;

    /**
     * First we initialize all the code generated for the GUI elements.
     * Then we change the values of the category Dropdown so it gets filled with
     * all the categories from the database.
     * And after that we fill the table with all the products at first and after 
     * that the user can filter all the products himself.
     */
    public InventoryList() {
       initComponents();
       initDropDownCategory();
       showInventory();
    }
    
    /**
     * This function retrieves all the categories from the database and puts all 
     * the product names in a list.
     * And after that the list is used to set the values for the filter category dropdown.
     */
    void initDropDownCategory() {
        List<Category> categories = WinkelApplication.getQueryManager().getCategories();
        
        String[] allcategories = new String[categories.size()+1];
        int i = 1;
        allcategories[0] = "Alles";
        for(Category cat : categories) {
            if(!cat.getName().equals("")) {
                allcategories[i] = cat.getName();
            }
            i++;
        }
        categoryDropDown.setModel(new javax.swing.DefaultComboBoxModel(allcategories));
    }
    
    /**
     * Here we pass the filter values to the "getAllProductsStock" function.
     * And we get a list of possible filtered products back.
     * We use this list add rows to the table with the product name and stock.
     * Before we add the new products the current table needs to be emptied.
     * Because we want to create a new list and not add the new results to the 
     * bottom of the old list.
     */
    void showInventory() {
        List<Product> products = WinkelApplication.getQueryManager().getAllProductsStock(this.filterCategory, this.filterProductName);    
        DefaultTableModel model = (DefaultTableModel) this.voorraadTabel.getModel();
        deleteAllRows(model);
        for (Product product : products) {
            model.addRow(
            new Object[] {
                product.getName(),
                product.getStock()
                   }
            );
        }
    }
    
    /**
     * This function empties the whole table to make place for new results.
     * @param model
     *  This is the tablemodel that needs to be emptied.
     */
    public void deleteAllRows( DefaultTableModel model ) {
        for( int i = model.getRowCount() - 1; i >= 0; i-- )
        {
            model.removeRow(i);
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        stockTitle = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        voorraadTabel = new javax.swing.JTable();
        editButton = new javax.swing.JButton();
        categoryDropDown = new javax.swing.JComboBox();
        nameProductInput = new javax.swing.JTextField();
        searchCheckbox = new javax.swing.JCheckBox();
        nameLabel = new javax.swing.JLabel();
        searchButton = new javax.swing.JButton();
        backButton = new javax.swing.JButton();
        resetButton = new javax.swing.JButton();

        stockTitle.setText("Voorraad");

        voorraadTabel.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Product", "Voorraad"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(voorraadTabel);

        editButton.setText("Bewerk");
        editButton.setToolTipText("");
        editButton.setAutoscrolls(true);
        editButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                editButtonActionPerformed(evt);
            }
        });

        categoryDropDown.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4", "BAMBAMBAM", "BASJDIJDSAOI", "dSAJODOSAI" }));
        categoryDropDown.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                categoryDropDownActionPerformed(evt);
            }
        });

        nameProductInput.setEnabled(false);
        nameProductInput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nameProductInputActionPerformed(evt);
            }
        });

        searchCheckbox.setText("Zoeken op naam");
        searchCheckbox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchCheckboxActionPerformed(evt);
            }
        });

        nameLabel.setText("Naam:");

        searchButton.setText("Zoek");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        backButton.setText("Terug");
        backButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButtonActionPerformed(evt);
            }
        });

        resetButton.setText("Reset");
        resetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resetButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(stockTitle)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(backButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 373, Short.MAX_VALUE)
                        .addComponent(editButton))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(categoryDropDown, 0, 180, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(nameLabel)
                                .addGap(71, 71, 71))
                            .addComponent(searchCheckbox)
                            .addComponent(nameProductInput, javax.swing.GroupLayout.DEFAULT_SIZE, 180, Short.MAX_VALUE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(searchButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE)
                                .addComponent(resetButton)))
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 307, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(stockTitle)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 374, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(editButton)
                            .addComponent(backButton)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(categoryDropDown, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(28, 28, 28)
                        .addComponent(searchCheckbox)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(nameLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(nameProductInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(searchButton)
                            .addComponent(resetButton))))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    /**
     * If the user has modified the stock values in the table he needs to confirm
     * that he wants the table to be edited.
     * This is done with the "editButton".
     * When clicked we loop through all the rows and receive the values of all the columns.
     * After that we give the values to the "updateProductStock" function who
     * updates all the values in the database.
     */
private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed
    DefaultTableModel model = (DefaultTableModel) this.voorraadTabel.getModel();
    int rowCount = model.getRowCount();
    
    for(int i=0;i<rowCount; i++) {
        Object productName = model.getValueAt(i, 0);
        Object productInventory = model.getValueAt(i, 1);
        
        String productName2 = productName.toString();
        try {
            int productInventory2 = Integer.parseInt(productInventory.toString());
            WinkelApplication.getQueryManager().updateProductStock(productName2, productInventory2);
        }
        catch(NullPointerException e) {
            JOptionPane.showMessageDialog(WinkelApplication.getInstance().getMainWindow(), "Voer aub een numerieke waarde in.", "Error", JOptionPane.ERROR_MESSAGE);
        }       
    }
}//GEN-LAST:event_editButtonActionPerformed

    private void searchCheckboxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchCheckboxActionPerformed
        if(this.searchCheckbox.isSelected() == true) {
            nameProductInput.setEnabled(true);
        }
        else {
            nameProductInput.setEnabled(false);
        }
    }//GEN-LAST:event_searchCheckboxActionPerformed

    private void nameProductInputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nameProductInputActionPerformed
    }//GEN-LAST:event_nameProductInputActionPerformed

    /**
     * This function passes the value of the "categoryDropdown" to a private variable.
     * And checks if the "searchCheckbox" is selected so it can decide to set the
     * "filterProductName" or not.
     * After that it calls the "showInventory" wich rebuilds the table according to 
     * the values of these 2 filter variable.
     */
    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed
        filterCategory = this.categoryDropDown.getSelectedItem().toString();
        if(this.searchCheckbox.isSelected() == true) {
            filterProductName = this.nameProductInput.getText();
        }
        else {
            filterProductName = null;
        }
        showInventory();
    }//GEN-LAST:event_searchButtonActionPerformed

    private void categoryDropDownActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_categoryDropDownActionPerformed
    }//GEN-LAST:event_categoryDropDownActionPerformed

    /**
     * This is the back button with leads you to the previous page.
     */
    private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
        WinkelApplication.window.previous();
    }//GEN-LAST:event_backButtonActionPerformed

    /**
     * This is the reset button.
     * If the reset button is pushed we need to set all the filter values to null.
     * So they wont be used again in the next rebuilding of the table values.
     * And we clear the values of the cleckbox and the input field.
     */
    private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetButtonActionPerformed
        filterCategory = null;
        filterProductName = null;
        this.searchCheckbox.setSelected(false);
        this.nameProductInput.setText("");
        this.showInventory();
        this.nameProductInput.setEnabled(false);
        this.categoryDropDown.setSelectedIndex(0);
    }//GEN-LAST:event_resetButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton backButton;
    private javax.swing.JComboBox categoryDropDown;
    private javax.swing.JButton editButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel nameLabel;
    private javax.swing.JTextField nameProductInput;
    private javax.swing.JButton resetButton;
    private javax.swing.JButton searchButton;
    private javax.swing.JCheckBox searchCheckbox;
    private javax.swing.JLabel stockTitle;
    private javax.swing.JTable voorraadTabel;
    // End of variables declaration//GEN-END:variables
}